import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export function useGeolocation() {
  const isLocating = ref(false)

  // 安全地转换为字符串，避免 [object Object] 问题
  const safeToString = (value: any): string => {
    if (value === null || value === undefined) return ''
    if (typeof value === 'string') return value
    if (typeof value === 'object') return ''
    return String(value)
  }

  // 执行逆地理编码
  const performReverseGeocoding = async (lng: number, lat: number) => {
    try {
      const response = await axios.get('/api/user/regions/amap/regeo', {
        params: {
          location: `${lng},${lat}`,
          radius: 1000,
          extensions: 'all'
        }
      })

      if (response.data?.status === '1' && response.data.regeocode) {
        const regeocode = response.data.regeocode
        const addressComponent = regeocode.addressComponent
        const formattedAddress = regeocode.formatted_address

        if (addressComponent?.province) {
          // 构建详细地址，确保所有值都是字符串
          let detailAddress = ''
          detailAddress += safeToString(addressComponent.township)
          detailAddress += safeToString(addressComponent.street)
          detailAddress += safeToString(addressComponent.streetNumber)

          // 如果没有详细地址组件，从格式化地址中提取
          if (!detailAddress && formattedAddress) {
            const provinceCity = `${addressComponent.province}${addressComponent.city}${addressComponent.district}`
            detailAddress = formattedAddress.replace(provinceCity, '') || '定位地址'
          }

          // 最终地址处理
          let finalAddress = detailAddress
          if (!finalAddress && addressComponent.building) {
            finalAddress = safeToString(addressComponent.building) || '定位地址'
          }
          if (!finalAddress) {
            finalAddress = '定位地址'
          }

          return {
            province: safeToString(addressComponent.province),
            city: safeToString(addressComponent.city),
            district: safeToString(addressComponent.district),
            street: finalAddress,
            region: [
              safeToString(addressComponent.province),
              safeToString(addressComponent.city),
              safeToString(addressComponent.district)
            ]
          }
        }
      }
      
      throw new Error('地址解析失败')
    } catch (error: any) {
      console.error('逆地理编码失败:', error)
      
      if (error.response?.status === 403) {
        ElMessage.error('API访问被拒绝，请检查密钥权限')
      } else if (error.response?.status === 400) {
        ElMessage.error('请求参数错误')
      } else {
        ElMessage.error('网络请求失败，请稍后重试')
      }
      
      throw error
    }
  }

  // 获取当前位置
  const getCurrentLocation = async () => {
    if (!navigator.geolocation) {
      ElMessage.warning('浏览器不支持地理位置服务')
      return null
    }

    if (isLocating.value) {
      ElMessage.warning('正在定位中，请稍候...')
      return null
    }

    isLocating.value = true
    ElMessage.info('正在获取位置信息...')

    try {
      // 检查本地存储的位置
      const savedLocation = localStorage.getItem('userLocation')
      if (savedLocation) {
        const location = JSON.parse(savedLocation)
        return await performReverseGeocoding(location.lng, location.lat)
      }

      // GPS定位
      const position = await new Promise<GeolocationPosition>((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, {
          timeout: 15000,
          enableHighAccuracy: true,
          maximumAge: 300000
        })
      })

      const lng = position.coords.longitude
      const lat = position.coords.latitude
      
      return await performReverseGeocoding(lng, lat)
    } catch (error: any) {
      let errorMessage = '获取位置失败'
      
      if (error.code === 1) {
        errorMessage = '位置访问被拒绝，请在浏览器设置中允许位置访问'
      } else if (error.code === 2) {
        errorMessage = '位置信息不可用'
      } else if (error.code === 3) {
        errorMessage = '获取位置超时'
      }
      
      ElMessage.error(errorMessage)
      return null
    } finally {
      isLocating.value = false
    }
  }

  return {
    isLocating,
    getCurrentLocation
  }
} 